package com.yuyou.fn.tradingservice.service.impl;

import com.github.wens.framework.service.impl.SuperServiceImpl;
import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.service.ISmsService;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.educational.entity.Campus;
import com.yuyou.fn.educational.entity.Room;
import com.yuyou.fn.educational.entity.SummerWinterDate;
import com.yuyou.fn.educational.service.ICampusService;
import com.yuyou.fn.educational.service.IRoomService;
import com.yuyou.fn.educational.service.ISummerWinterDateService;
import com.yuyou.fn.platform.entity.SysUser;
import com.yuyou.fn.platform.permission.DataPermission;
import com.yuyou.fn.platform.service.ISysDataPermissionService;
import com.yuyou.fn.tradingservice.entity.LeaseMessage;
import com.yuyou.fn.tradingservice.entity.PersonLeaseMessage;
import com.yuyou.fn.tradingservice.entity.ServiceProduct;
import com.yuyou.fn.tradingservice.mapper.ServiceProductMapper;
import com.yuyou.fn.tradingservice.service.*;
import com.yuyou.fn.tradingservice.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * ServiceProduct 表数据服务层接口实现类
 *
 */
@Service
public class ServiceProductServiceImpl extends SuperServiceImpl<ServiceProductMapper, ServiceProduct,Long> implements IServiceProductService {


    @Resource
    private IServiceCategoryService categoryService;



    @Resource
    private ICampusService campusService;

    @Resource
    private IRoomService roomService;


    @Resource
    private ILeaseMessageService leaseMessageService;

    @Resource
    private IPersonLeaseMessageService personLeaseMessageService;


    @Resource
    private ISmsService smsService;

    @Resource
    private ISysDataPermissionService sysDataPermissionService;

    @Resource
    private ISummerWinterDateService summerWinterDateService;

    @Resource
    private IServiceProductListingService serviceProductListingService;

    private static String[] weekNameArray={"周日","周一","周二","周三","周四","周五","周六"};

    @Override
    public ServiceLeaseProductDetail pullAllTimeStr(ServiceProduct serviceProduct) {
        ServiceLeaseProductDetail serviceLeaseProductDetail=new ServiceLeaseProductDetail();
        BeanUtils.copyProperties(serviceLeaseProductDetail,serviceProduct);
        LeaseMessageQueryVo leaseMessageQueryVo=new LeaseMessageQueryVo();
        leaseMessageQueryVo.setProductId(serviceProduct.getProductId());
        List<LeaseMessage> leaseMessageList=leaseMessageService.findLeaseMessage(leaseMessageQueryVo);
        StringBuffer allTime=new StringBuffer();
        for (LeaseMessage leaseMessage:leaseMessageList){
            allTime.append(leaseMessage.getTimeDesc()+"\n");
        }
        serviceLeaseProductDetail.setAllTimeStr(allTime.toString().trim());


        return  serviceLeaseProductDetail;
    }

    @Override
    public ServiceLeaseProductDetail leaseProductDetail(ServiceProduct serviceProduct) {
        SimpleDateFormat sdf =   new SimpleDateFormat( " yyyy-MM-dd" );
        ServiceLeaseProductDetail serviceLeaseProductDetail=new ServiceLeaseProductDetail();
        BeanUtils.copyProperties(serviceLeaseProductDetail,serviceProduct);
        LeaseMessageQueryVo leaseMessageQueryVo=new LeaseMessageQueryVo();
        leaseMessageQueryVo.setProductId(serviceProduct.getProductId());
        TreeMap<String,List<LeaseMessage>> timeMap=new TreeMap<>();
        List<LeaseMessage> leaseMessageList=leaseMessageService.findLeaseMessage(leaseMessageQueryVo);
        List<LeaseMessage> tempLeaseMessageList=null;
        for (LeaseMessage leaseMessage:leaseMessageList){
            if (leaseMessage.getsWDayPrice()!=null){
                String year=Utils.formatDate(leaseMessage.getStart(),"yyyy");
                SummerWinterDate summerWinterDate=summerWinterDateService.findByCampusIdAndYear(leaseMessage.getCampusId(),year);
                if(summerWinterDate!=null){
                    leaseMessage.setSummerStartDate(summerWinterDate.getSummerStartDate());
                    leaseMessage.setSummerEndDate(summerWinterDate.getSummerEndDate());
                    leaseMessage.setWinterStartDate(summerWinterDate.getWinterStartDate());
                    leaseMessage.setWinterEndDate(summerWinterDate.getWinterEndDate());
                }
            }
            Date start=leaseMessage.getStart();
            Date end=leaseMessage.getEnd();
            String dateStr=sdf.format(start)+" "+sdf.format(end);
            if (timeMap.containsKey(dateStr)){
                tempLeaseMessageList=timeMap.get(dateStr);
                tempLeaseMessageList.add(leaseMessage);
            }else {
                tempLeaseMessageList=new ArrayList<LeaseMessage>();
                tempLeaseMessageList.add(leaseMessage);
                timeMap.put(dateStr,tempLeaseMessageList);
            }
        }

        serviceLeaseProductDetail.setTimeMap(timeMap);
        return serviceLeaseProductDetail;
    }

    @Override
    public ServiceLeaseProductDetail leaseProductDetail(Long productId,Integer path) {
        ServiceProduct serviceProduct=this.findById(productId);
        if (path==0 &&(serviceProduct == null || serviceProduct.getStatus() == 0)) {
            throw  new BusException("出租信息不存在或者已下架");
        }
        ServiceLeaseProductDetail serviceLeaseProductDetail=null;
        if (serviceProduct!=null){
            serviceLeaseProductDetail=this.leaseProductDetail(serviceProduct);
        }
        return serviceLeaseProductDetail;
    }

    @Override
    public List<ServiceProduct> findByInventoryAndStatusAndType(Integer type,Integer inventory, Integer status) {
        Example<ServiceProduct> serviceProductExample=ServiceProduct.createExample();
        Example.Criteria criteria=serviceProductExample.createCriteria();
        criteria.andEqualTo("type",type);
        criteria.andEqualTo("inventory",inventory);
        criteria.andEqualTo("status",status);
        return findListByExample(serviceProductExample);
    }

    @Override
    public void offProduct(Long productId,Integer status) {
        ServiceProduct serviceProduct=new ServiceProduct();
        serviceProduct.setProductId(productId);
        serviceProduct.setStatus(status);
        updateSelectiveById(serviceProduct);

        ServiceProduct  serviceProduct1=this.findById(productId);
        try{
            smsService.send(Arrays.asList(serviceProduct1.getSellerPhoneNo()),"您好，您发布的信息含有非法内容或不符合现实情况等原因，被管理员强制下架/删除，请检查修改后重新发布，谢谢！");
        }
        catch (Exception e){
        }
    }

    @Override
    @Transactional
    public void saveOrUpdateGoods(ProductVo productVo, SysUser sysUser) {
        ServiceProduct serviceProduct = new ServiceProduct();
        if (StringUtils.isEmpty(productVo.getImageUrl()) && StringUtils.isNotEmpty(productVo.getAllImageUrls())){
            productVo.setImageUrl(productVo.getAllImageUrls().split(",")[0]);
        }

        BeanUtils.copyProperties(serviceProduct, productVo);
        if (serviceProduct.getType()==null){
            throw  new BusException("请传入type");
        }
        if (serviceProduct.getProfitMainAccountId()==null){
            throw  new BusException("请传入收款主体");
        }


        if(serviceProduct.getProductId() == null) {
            serviceProduct.setCreateTime(TimeUtils.now());
            serviceProduct.setUpdateTime(TimeUtils.now());
            serviceProduct.setSellerId(sysUser.getUserId());
            serviceProduct.setSellerName(sysUser.getUsername());
            serviceProduct.setSellerPhoneNo(sysUser.getPhoneNo());
            serviceProduct.setVendorName(sysUser.getRealName());
            this.insertSelective(serviceProduct);
        } else {
          /*  ServiceProduct serviceProduct1=this.findById(serviceProduct.getProductId());
            if (serviceProduct1.getStatus()==1){
                throw new BusException("请下架后再修改");
            }*/
            ServiceProduct serviceProduct1=this.findById(serviceProduct.getProductId());
            Integer inventory=serviceProduct1.getInventory()+serviceProduct.getInventory();
            if (inventory<0) {
                inventory=0;
            }
            serviceProduct.setUpdateTime(TimeUtils.now());
            serviceProduct.setInventory(inventory);
            this.updateSelectiveById(serviceProduct);
            /*单价信息发生变动，将存在的购物车信息置为失效*/
           /* if (!serviceProduct.getUnitPrice().equals(serviceProduct1.getUnitPrice())){
                serviceProductListingService.updateEffectiveness(serviceProduct.getProductId(),0,"供应信息发生变动，购物车失效");
            }*/
        }

        //serviceImageService.createProductImages(serviceProduct,productImages);
    }

    @Override
    public void saveOrUpdateDemand(DemandVo demandVo, SysUser sysUser) {
        ServiceProduct serviceProduct = new ServiceProduct();
        BeanUtils.copyProperties(serviceProduct, demandVo);
        if(serviceProduct.getProductId() == null) {
            serviceProduct.setCreateTime(TimeUtils.now());
            serviceProduct.setUpdateTime(TimeUtils.now());
            serviceProduct.setSellerId(sysUser.getUserId());
            serviceProduct.setSellerName(sysUser.getUsername());
            serviceProduct.setSellerPhoneNo(sysUser.getPhoneNo());
            serviceProduct.setVendorName(sysUser.getRealName());
            this.insertSelective(serviceProduct);
        } else {
            serviceProduct.setUpdateTime(TimeUtils.now());
            this.updateSelectiveById(serviceProduct);
        }
    }

    @Override
    public void changeStatus(Long productId, Integer status) {
        ServiceProduct serviceProduct=new ServiceProduct();
        serviceProduct.setProductId(productId);
        serviceProduct.setStatus(status);
        this.updateSelectiveById(serviceProduct);
    }

/*    @Override
    @Transactional
    public void saveOrUpdateLeaseProducts(List<LeaseMessage> leaseMessageList, LeaseVo leaseVo, SysUser sysUser) {
        for (LeaseMessage leaseMessage:leaseMessageList){
            this.saveOrUpdateLeaseProduct(Arrays.asList(leaseMessage), leaseVo, sysUser);
        }
    }*/

    @Override
    public Long countServiceProductByCategoryId(Long categoryId) {
        Example<ServiceProduct> serviceProductExample=ServiceProduct.createExample();
        Example.Criteria criteria=serviceProductExample.createCriteria();
        criteria.andEqualTo("categoryId",categoryId);
        return countByExample(serviceProductExample);
    }

    @Override
    public ServiceProduct findBySellerIdAndRoomId(Long sellerId, Long roomId) {
        Example<ServiceProduct> serviceProductExample=ServiceProduct.createExample();
        Example.Criteria criteria=serviceProductExample.createCriteria();
        criteria.andEqualTo("sellerId",sellerId);
        criteria.andEqualTo("roomId",roomId);

        return findOneByExample(serviceProductExample);
    }

    @Override
    public ServiceProduct findBySellerIdRoomIdProfitId(Long sellerId, Long roomId, Long profitMainAccountId) {
        Example<ServiceProduct> serviceProductExample=ServiceProduct.createExample();
        Example.Criteria criteria=serviceProductExample.createCriteria();
        criteria.andEqualTo("sellerId",sellerId);
        criteria.andEqualTo("roomId",roomId);
        criteria.andEqualTo("profitMainAccountId",profitMainAccountId);
        return findOneByExample(serviceProductExample);
    }

    @Override
    public void checkIfRelease(Long sellerId, Long roomId,Long profitMainAccountId) {
        ServiceProduct serviceProduct=this.findBySellerIdRoomIdProfitId(sellerId,roomId,profitMainAccountId);
        if (serviceProduct!=null){
            throw new BusException(serviceProduct.getProductId()+"$已经发布过该课室，请前往编辑修改");
        }
    }

    @Override
    public Page<ServiceProduct> findProductPageByQueryVo(ProductQueryVo productQueryVo, int pageNo, int pageSize) {
        Example<ServiceProduct> example = ServiceProduct.createExample();

        Example.Criteria criteria = example.createCriteria();


        if (productQueryVo.getMinStartDate()!=null){
            criteria.andGreaterThanOrEqualTo("maxEndDate",TimeUtils.changeOneDateLastTime(productQueryVo.getMinStartDate()));
        }
        if (productQueryVo.getMaxEndDate()!=null){
            criteria.andLessThanOrEqualTo("minStartDate",productQueryVo.getMaxEndDate());
        }
        if (StringUtils.isNotEmpty(productQueryVo.getTimeTypes())){
            criteria.andLike("timeTypes","%"+productQueryVo.getTimeTypes()+"%");
        }

        if (StringUtils.isNotEmpty(productQueryVo.getCategoryIdLike())){
            criteria.andLike("categoryIds","%"+productQueryVo.getCategoryIdLike()+"%");
        }


        if (productQueryVo.getAreaTeamId()!=null){
            //criteria.andLike("useAreaTeamIds","%"+productQueryVo.getAreaTeamId().toString()+"%");
           // criteria.andCondition( " (use_area_team_ids like '%"+productQueryVo.getAreaTeamId().toString()+"%' or use_area_team_ids ='')");
            criteria.andLike("useAreaTeamIds","%"+productQueryVo.getAreaTeamId()+"%");
        }
        if (productQueryVo.getTimeInterval()!=null){
            Date date = new Date();
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.DATE,-productQueryVo.getTimeInterval());
            criteria.andGreaterThanOrEqualTo("createTime",cal.getTime());
        }

        if (productQueryVo.getSellerId()!=null){
            criteria.andEqualTo("sellerId",productQueryVo.getSellerId());
        }

        if (productQueryVo.getBeginTime()!=null){
            criteria.andGreaterThanOrEqualTo("updateTime",productQueryVo.getBeginTime());
        }
        if(productQueryVo.getEndTime()!=null){
            criteria.andLessThanOrEqualTo("updateTime",TimeUtils.changeOneDateLastTime(productQueryVo.getEndTime() ));
        }

        if (StringUtils.isNotEmpty(productQueryVo.getSellerName())){
            criteria.andLike("sellerName","%"+productQueryVo.getSellerName()+"%");
        }

        if (StringUtils.isNotEmpty(productQueryVo.getSellerPhoneNo())){
            criteria.andLike("sellerPhoneNo","%"+productQueryVo.getSellerPhoneNo()+"%");
        }

        if (productQueryVo.getType()!=null ){
            criteria.andEqualTo("type", productQueryVo.getType());
        }

        if (StringUtils.isNotEmpty(productQueryVo.getProductName())){
            criteria.andLike("productName", "%"+productQueryVo.getProductName()+"%");
        }

        if (productQueryVo.getCategoryId()!=null ){
            criteria.andEqualTo("categoryId", productQueryVo.getCategoryId());
        }
        if (productQueryVo.getStatus()!=null){
            criteria.andEqualTo("status",productQueryVo.getStatus());
        }

        if (productQueryVo.getMonthlyPurchaseNumber()!=null && productQueryVo.getMonthlyPurchaseNumber()==0){//0正序
            example.orderBy("monthlyPurchaseNumber");
        }else if(productQueryVo.getMonthlyPurchaseNumber()!=null && productQueryVo.getMonthlyPurchaseNumber()==1){//倒序
            example.orderBy("monthlyPurchaseNumber").desc();
        }

        if (productQueryVo.getAmount()!=null && productQueryVo.getAmount()==0){//0正序
            example.orderBy("amount");
        }else if(productQueryVo.getAmount()!=null && productQueryVo.getAmount()==1){//倒序
            example.orderBy("amount").desc();
        }
        if (productQueryVo.getPrice()!=null && productQueryVo.getPrice().equals(new BigDecimal(0))){//0正序
            example.orderBy("unitPrice");

        }else if(productQueryVo.getPrice()!=null && productQueryVo.getPrice().equals(new BigDecimal(1))){//倒序
            example.orderBy("unitPrice").desc();
        }

        if (productQueryVo.getCategoryId()!=null){
            criteria.andEqualTo("categoryId",productQueryVo.getCategoryId());
        }

        example.orderBy("createTime").desc();
        return findPageByExample(example, pageNo, pageSize);
    }

    @Override
    public Page<ServiceLeaseProductDetail> findLeaseProductByQueryVo(ProductQueryVo productQueryVo, int pageNo, int pageSize) {
        Page<ServiceProduct> serviceProductPage=this.findProductPageByQueryVo(productQueryVo,pageNo,pageSize);
        Page<ServiceLeaseProductDetail> serviceLeaseProductDetailPage=Utils.newPage(serviceProductPage);
        if (serviceProductPage.getRecords()!=null){
            List<ServiceLeaseProductDetail> leaseProductDetailList=new ArrayList<ServiceLeaseProductDetail>(serviceProductPage.getRecords().size());
            for (ServiceProduct serviceProduct:serviceProductPage.getRecords()){
                ServiceLeaseProductDetail serviceLeaseProductDetail=this.pullAllTimeStr(serviceProduct);
                leaseProductDetailList.add(serviceLeaseProductDetail);
            }
            serviceLeaseProductDetailPage.setRecords(leaseProductDetailList);
            return  serviceLeaseProductDetailPage;
        }
        return null;
    }


    @Override
    public List<ServiceProduct> findOrderByCreateTime(Integer status, Integer limit) {
        Example<ServiceProduct> serviceProductExample=ServiceProduct.createExample();
        Example.Criteria criteria=serviceProductExample.createCriteria();
        criteria.andEqualTo("status",status);
        serviceProductExample.orderBy("updateTime").desc();
        serviceProductExample.limit(limit);
        return this.findListByExample(serviceProductExample);
    }












    @Override
    public void deleteProduct(Long categoryId) {
        if(categoryId == null ){
            throw new NullPointerException();
        }
        Example<ServiceProduct> example = ServiceProduct.createExample();
        example.createCriteria().andEqualTo("categoryId", categoryId);
        this.deleteByExample(example);
    }

    @Override
    public List<ServiceProduct> findProductsByCategoryId(Long categoryId) {
        Example<ServiceProduct> example = ServiceProduct.createExample();
        example.createCriteria().andEqualTo("categoryId", categoryId);
        return this.findListByExample(example);
    }

    @Override
    public List<ServiceProduct> productDetail(Long categoryId) {
        List<Long> categoryIds = categoryService.getAllChildCategory(categoryId);
        categoryIds.add(categoryId);
        List<ServiceProduct> productList = new ArrayList<>();
        for (Long id : categoryIds) {
            Example<ServiceProduct> example = ServiceProduct.createExample();
            example.createCriteria().andEqualTo("categoryId", id);
            productList.addAll(this.findListByExample(example));
        }
        return productList;
    }

    public void fillExtraData(ServiceProduct product) {
    /*    if (product.getTeamId() != null) {
            product.setBusTeamName(busTeamService.findTeamNameById(product.getTeamId()));
        } else {
            product.setTeamId(0L);
            product.setBusTeamName("");
        }*/
        if (product.getCategoryId() != null) {
            product.setCategoryName(categoryService.findCategoryNameById(product.getCategoryId()));
        } else {
            product.setCategoryId(0L);
            product.setCategoryName("");
        }
        if (product.getCampusId()!=null){
            product.setCampusName(campusService.findCampusNameByCampusId(product.getCampusId()));
        }else {
            product.setCampusName("");
            product.setCampusId(0L);
        }
    }

    @Override
    public ServiceProduct findProductMaxAmountByType(Integer type) {
        Example<ServiceProduct> example = ServiceProduct.createExample();
        example.createCriteria().andEqualTo("type", type);
        example.orderBy("amount").desc();
        example.limit(1);
        return findOneByExample(example);
    }

    @Override
    public void deleteProductById(Long productId) {
        ServiceProduct product=this.findById(productId);
        Integer status=product.getStatus();
        if (status==1){
            throw new BusException("请先下架再删除");
        }
        this.deleteById(productId);
    }

    @Override
    @Transactional
    public void deleteProductByUserIdAndProductId(Long userId, List<Long> productIds,Integer path) {
        Example<ServiceProduct> example=ServiceProduct.createExample();
        Example.Criteria criteria=example.createCriteria();
        if (path==1){
            criteria.andEqualTo("sellerId",userId);
        }
        criteria.andIn("productId",productIds);
        deleteByExample(example);
        leaseMessageService.deleteByProductIds(productIds);
    }

    @Override
    @Transactional
    public void onOrOff(SysUser user, Long productId,Integer status,Integer path) {
        Example<ServiceProduct> example=ServiceProduct.createExample();
        Example.Criteria criteria=example.createCriteria();
        if (path==1){
            criteria.andEqualTo("sellerId",user.getUserId());
        }
        criteria.andEqualTo("productId",productId);
        ServiceProduct serviceProductVo=new ServiceProduct();
        serviceProductVo.setProductId(productId);
        serviceProductVo.setStatus(status);
        ServiceProduct serviceProduct=this.findById(productId);
        /*租赁上架需要判断时间*/
        if (serviceProduct.getType()==2 && status==1){
            LeaseMessageQueryVo leaseMessageQueryVo=new LeaseMessageQueryVo();
            leaseMessageQueryVo.setProductId(productId);
            List<LeaseMessage> leaseMessageList=leaseMessageService.findLeaseMessage(leaseMessageQueryVo);
            leaseMessageService.canLease(user,leaseMessageList,serviceProduct);
            leaseMessageService.updateStatusByProductId(productId,status);

        }else if (serviceProduct.getType()==2 && status==0 ){//租赁信息下架判断全部时间段是否全部下架
            leaseMessageService.updateStatusByProductId(productId,status);
        }

        if (status==0 && path==0){
            String name=serviceProduct.getType()==2?"租赁":serviceProduct.getType()==0?"商品":"需求";
            try{
                smsService.send(Arrays.asList(serviceProduct.getSellerPhoneNo()),"您好，您发布的"+name+"信息"+serviceProduct.getProductName()+"含有非法内容或不符合现实情况等原因，被管理员强制下架/删除，请检查修改后重新发布，谢谢！");
            }catch (Exception e){
            }
        }


        updateSelectiveByExample(serviceProductVo,example);
    }



    @Override
    public HashMap<Long, Object> findOwnPlaceList(SysUser sysUser) {
        HashMap<Long,Object> result=new HashMap<Long,Object>();
        DataPermission dataPermission = sysDataPermissionService.findDataPermissionForUser(sysUser.getUserId());
        List<Long> areaTeamIdList=dataPermission.getAreaTeamIds();

        List<Campus> campusList = campusService.findByIdsAndStateAndAreaTeamIds(1, areaTeamIdList);

        for (Campus campus : campusList) {
            HashMap<String, Object> oneResultMap = new HashMap<String, Object>();
            oneResultMap.put("campus", campus);
            List<Room> roomList = roomService.findListByCampusId(campus.getCampusId(), null, null);
            oneResultMap.put("roomList", roomList);
            result.put(campus.getCampusId(), oneResultMap);
        }



        /*该用户该课室租赁付款成功且结束时间不超过当前时间的租赁信息*/
        PersonLeaseQueryVo personLeaseQueryVo=new PersonLeaseQueryVo();
        personLeaseQueryVo.setBuyerId(sysUser.getUserId());
        personLeaseQueryVo.setLeaseState(1);
        List<PersonLeaseMessage> personLeaseMessageList=personLeaseMessageService.findPersonLeaseMessage(personLeaseQueryVo);

        HashMap<Long,Object> otherResult=new HashMap<Long,Object>();
        for (PersonLeaseMessage personLeaseMessage:personLeaseMessageList){
            if(result.containsKey(personLeaseMessage.getCampusId())) continue;
            HashMap<String,Object> oneOtherResult=null;
            List<Room> roomList=null;
            if(otherResult.containsKey(personLeaseMessage.getCampusId())){
                oneOtherResult=(HashMap<String,Object>)otherResult.get(personLeaseMessage.getCampusId());
                roomList= ( List<Room>)oneOtherResult.get("roomList");
            }else{
                Campus campus=new Campus();
                campus.setCampusId(personLeaseMessage.getCampusId());
                campus.setCampusName(personLeaseMessage.getCampusName());
                oneOtherResult=new HashMap<String,Object>();
                oneOtherResult.put("campus",campus);
                roomList=new ArrayList<Room>();
            }
            List<Long> roomIdList=BeanUtils.toList(roomList,"roomId");
            if (roomIdList.contains(personLeaseMessage.getRoomId())) {
                continue;
            }
            Room room=new Room();
            room.setCampusId(personLeaseMessage.getCampusId());
            room.setRoomId(personLeaseMessage.getRoomId());
            room.setRoomName(personLeaseMessage.getRoomName());
            roomList.add(room);
            oneOtherResult.put("roomList",roomList);
            otherResult.put(personLeaseMessage.getCampusId(),oneOtherResult);
        }
        result.putAll(otherResult);
        return result;
    }



    @Override
    @Transactional
    public ServiceProduct saveLeaseProduct(LeaseVo leaseVo,SysUser sysUser, List<LeaseMessagePriceVo> leaseMessagePriceVoList) {
        if (leaseVo.getProfitMainAccountId()==null){
            throw  new BusException("收益主体必须输入");
        }

        ServiceProduct serviceProduct = new ServiceProduct();
        if (StringUtils.isEmpty(leaseVo.getImageUrl()) && StringUtils.isNotEmpty(leaseVo.getAllImageUrls())){
            leaseVo.setImageUrl(leaseVo.getAllImageUrls().split(",")[0]);
        }
        BeanUtils.copyProperties(serviceProduct,leaseVo);

        if (serviceProduct.getType()==null){
            throw new BusException("请输入租赁产品的类型");
        }
        if (serviceProduct.getCategoryId()==null){
            throw new BusException("请输入产品分类");
        }
        if (serviceProduct.getCampusId()==null){
            throw new BusException("请选择具体校区");
        }
        if (serviceProduct.getRoomId()==null){
            throw new BusException("请选择具体课室");
        }
        if (leaseMessagePriceVoList==null || leaseMessagePriceVoList.size()<=0){
            throw new BusException("请选择具体时间段出租");
        }
        String contactName=serviceProduct.getContactName();
        Campus campus=campusService.findById(serviceProduct.getCampusId());
        Room room=roomService.findById(serviceProduct.getRoomId());
        BeanUtils.copyProperties(serviceProduct,campus);
        BeanUtils.copyProperties(serviceProduct,room);
        serviceProduct.setSellerId(sysUser.getUserId());
        serviceProduct.setContactName(contactName);
        serviceProduct.setSellerName(sysUser.getUsername());
        serviceProduct.setSellerPhoneNo(sysUser.getPhoneNo());
        serviceProduct.setUpdateTime(TimeUtils.now());
        serviceProduct.setProductName(campus.getCampusName()+" "+room.getRoomName());
        serviceProduct.setVendorName(sysUser.getRealName());
        if (serviceProduct.getProductId()!=null){
            this.updateSelectiveById(serviceProduct);
            leaseMessageService.deleteByProductIds(Arrays.asList(serviceProduct.getProductId()));
        }else{
            ServiceProduct serviceProduct1=this.findBySellerIdRoomIdProfitId(serviceProduct.getSellerId(),serviceProduct.getRoomId(),leaseVo.getProfitMainAccountId());
            if (serviceProduct1!=null){
                throw new BusException("该课室该收益主体已经发布过租赁,请前往编辑");
             /*   serviceProduct.setProductId(serviceProduct1.getProductId());
                this.updateSelectiveById(serviceProduct);
                leaseMessageService.deleteByProductIds(Arrays.asList(serviceProduct.getProductId()));*/
            }else{
                serviceProduct.setCreateTime(TimeUtils.now());
                this.insertSelective(serviceProduct);
            }

        }
        List<LeaseMessage> leaseMessageList=leaseMessageService.saveLeaseMessage(sysUser,leaseMessagePriceVoList,serviceProduct);
        Date minStartDate=null;
        Date maxEndDate=null;
        for (LeaseMessage leaseMessage:leaseMessageList){
            if (maxEndDate==null){
                maxEndDate=leaseMessage.getEnd();
            }
            if (minStartDate==null){
                minStartDate=leaseMessage.getStart();
            }
            if (leaseMessage.getStart().before(minStartDate)){
                minStartDate=leaseMessage.getStart();
            }
            if (leaseMessage.getEnd().after(maxEndDate)){
                maxEndDate=leaseMessage.getEnd();
            }

        }
        ServiceProduct newServiceProduct=new ServiceProduct();
        newServiceProduct.setProductId(serviceProduct.getProductId());
        newServiceProduct.setMinStartDate(minStartDate);
        newServiceProduct.setMaxEndDate(maxEndDate);
        newServiceProduct.setUpdateTime(TimeUtils.now());
        this.updateSelectiveById(newServiceProduct);

        return newServiceProduct;
    }

    @Override
    public TreeMap<String, List<String>> findLeaseTimeTable(Date startDate, Date endDate,String startTime,String endTime, Long roomId, SysUser sysUser,Integer minutes,Long profitMainAccountId){
        Room room=roomService.findById(roomId);
        Boolean noHave=this.checkHaveAllRoomTime(profitMainAccountId,room.getCampusId());
        LeaseMessageQueryVo leaseMessageQueryVo=new LeaseMessageQueryVo();
        leaseMessageQueryVo.setStatus(1);
        leaseMessageQueryVo.setRoomId(roomId);
        leaseMessageQueryVo.setStart(startDate);
        leaseMessageQueryVo.setEnd(endDate);
        leaseMessageQueryVo.setSellerId(sysUser.getUserId());
        leaseMessageQueryVo.setProfitMainAccountId(profitMainAccountId);
        List<LeaseMessage> leaseMessageList=leaseMessageService.findLeaseMessage(leaseMessageQueryVo);
        List<TimeStampLong> timeStampLongList=new ArrayList<TimeStampLong>();
        List<TimeStampLong> fromTimeStampLongList=new ArrayList<TimeStampLong>();
        List<TimeStampLong> buyTimeStampLongList=new ArrayList<TimeStampLong>();
        List<TimeStampLong> noHaveTimeStampLongList=new ArrayList<TimeStampLong>();
        List<String> sourcePersonIds=new ArrayList<String>();
        for (LeaseMessage leaseMessage:leaseMessageList){
            if (StringUtils.isNotEmpty(leaseMessage.getSourcePersonLeaseIds())){
                sourcePersonIds.add(leaseMessage.getSourcePersonLeaseIds());
            }
            TimeStampLong timeStampLong=new TimeStampLong();
            timeStampLong.setStartTimeStamp(TimeUtils.toMini(leaseMessage.getStart()));
            timeStampLong.setEndTimeStamp(TimeUtils.toMini(TimeUtils.changeDateByNum(leaseMessage.getEnd(),1)));
            timeStampLongList.add(timeStampLong);
        }
        if (sourcePersonIds.size()>0){
            List<PersonLeaseMessage> formPersonLeaseMessageList=personLeaseMessageService.findByIds(Utils.toLongIds(StringUtils.join(sourcePersonIds,",")));
            for (PersonLeaseMessage personLeaseMessage:formPersonLeaseMessageList){
                fromTimeStampLongList.addAll(personLeaseMessageService.findTimeStampLongByPersonLease(personLeaseMessage));
            }
        }


        if (noHave){
            PersonLeaseQueryVo personLeaseQueryVo=new PersonLeaseQueryVo();
            //personLeaseQueryVo.setDateQueryCode(1);
            personLeaseQueryVo.setRoomId(roomId);
            personLeaseQueryVo.setLeaseState(1);
            personLeaseQueryVo.setBuyerId(sysUser.getUserId());
            personLeaseQueryVo.setPayMainAccountId(profitMainAccountId);
            List<PersonLeaseMessage> personLeaseMessageList=personLeaseMessageService.findPersonLeaseMessage(personLeaseQueryVo);
            List<String> conflictIds=new ArrayList<String>();
            for (PersonLeaseMessage personLeaseMessage:personLeaseMessageList){
                buyTimeStampLongList.addAll(personLeaseMessageService.findTimeStampLongByPersonLease(personLeaseMessage));
                if (StringUtils.isNotEmpty(personLeaseMessage.getConfictIds())){
                    conflictIds.add(personLeaseMessage.getConfictIds());
                }
            }
            String str=StringUtils.join(conflictIds,",");
            if (conflictIds.size()>0 && StringUtils.isNotEmpty(str)){
                List<PersonLeaseMessage> noHaveList = personLeaseMessageService.findByIds(Utils.toLongIds(str));
                for (PersonLeaseMessage personLeaseMessage:noHaveList){
                    noHaveTimeStampLongList.addAll(personLeaseMessageService.findTimeStampLongByPersonLease(personLeaseMessage));
                }
            }
        }


        TreeMap<String,List<String>> resultMap=new TreeMap<String,List<String>>();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat1=new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            while (startDate.before(endDate) || startDate.equals(endDate)){
                List<String> list=new ArrayList<String>();
                String dayStart=simpleDateFormat.format(startDate);
                String start=dayStart+" "+startTime;
                String end=dayStart+" "+endTime;
                Date tempStartDate=simpleDateFormat1.parse(start);
                Date endStartDate=simpleDateFormat1.parse(end);
                while (tempStartDate.before(endStartDate)){
                    int startStamp=TimeUtils.toMini(tempStartDate);
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(tempStartDate);
                    cal.add(Calendar.MINUTE, minutes);
                    tempStartDate=cal.getTime();
                    int endStamp=TimeUtils.toMini(tempStartDate);
                /*1可以使用，0已被购买，2不可使用*/
                    String s="1";
                    if (noHave){
                        s="2";
                    }
                    for (TimeStampLong checkTimeStampLong : buyTimeStampLongList) {
                        int checkStart = checkTimeStampLong.getStartTimeStamp();
                        int checkEnd = checkTimeStampLong.getEndTimeStamp();
                        if (startStamp >= checkStart && endStamp <= checkEnd) {
                            s = "1";
                            break;
                        }
                    }
                    for (TimeStampLong checkTimeStampLong:timeStampLongList){
                        int checkStart=checkTimeStampLong.getStartTimeStamp();
                        int checkEnd=checkTimeStampLong.getEndTimeStamp();
                        if(startStamp>=checkEnd || endStamp<=checkStart) {
                            continue;
                        }else{
                            s="0";
                            break;
                        }
                    }
                    if ("0".equals(s)){
                        for (TimeStampLong checkTimeStampLong:fromTimeStampLongList){
                            int checkStart=checkTimeStampLong.getStartTimeStamp();
                            int checkEnd=checkTimeStampLong.getEndTimeStamp();
                            if(startStamp>=checkStart && endStamp<=checkEnd) {
                                s="0";
                                break;
                            }else{
                                s="2";
                            }
                        }
                    }
                    if (noHave && "1".equals(s)) {
                        for (TimeStampLong checkTimeStampLong : noHaveTimeStampLongList) {
                            int checkStart = checkTimeStampLong.getStartTimeStamp();
                            int checkEnd = checkTimeStampLong.getEndTimeStamp();
                            if (startStamp >= checkStart && endStamp <= checkEnd) {
                                s = "2";
                                break;
                            }
                        }
                    }
                    list.add(s);

                }
                int weekNum=TimeUtils.getWeekOfDate(startDate);
                String weekName=weekNameArray[weekNum];
                list.add(0,weekName);
                resultMap.put(simpleDateFormat.format(startDate),list);
                Calendar cal = Calendar.getInstance();
                cal.setTime(startDate);
                cal.add(Calendar.DATE,1);
                startDate=cal.getTime();
            }
        }catch (Exception e){
            throw  new BusException(e.getMessage());
        }

        return resultMap;
    }

    @Override
    public TreeMap<String,List<String>> findPersonLeaseTimeTable(Date startDate, Date endDate, String startTime, String endTime, Long productId, Integer minutes){
        LeaseMessageQueryVo leaseMessageQueryVo=new LeaseMessageQueryVo();
        leaseMessageQueryVo.setProductId(productId);
        leaseMessageQueryVo.setStatus(1);
        List<LeaseMessage> leaseMessageList=leaseMessageService.findLeaseMessage(leaseMessageQueryVo);
        List<TimeStampLong> allTimeStampLongList=new ArrayList<TimeStampLong>();
        List<TimeStampLong> canTimeStampLongList=new ArrayList<TimeStampLong>();
        List<String> sourcePersonLeaseIds=new ArrayList<String>();
        for (LeaseMessage leaseMessage:leaseMessageList){
            TimeStampLong timeStampLong=new TimeStampLong();
            timeStampLong.setStartTimeStamp(TimeUtils.toMini(leaseMessage.getStart()));
            timeStampLong.setEndTimeStamp(TimeUtils.toMini(TimeUtils.changeDateByNum(leaseMessage.getEnd(),1)));
            allTimeStampLongList.add(timeStampLong);
            if (StringUtils.isNotEmpty(leaseMessage.getSourcePersonLeaseIds())){
                sourcePersonLeaseIds.add(leaseMessage.getSourcePersonLeaseIds());
            }
        }

        if (sourcePersonLeaseIds.size()>0){
            String allStr=StringUtils.join(sourcePersonLeaseIds,",");
            List<PersonLeaseMessage> sourcePersonLeaseMessageList=personLeaseMessageService.findByIds(Utils.toLongIds(allStr));
            for (PersonLeaseMessage personLeaseMessage:sourcePersonLeaseMessageList){
                canTimeStampLongList.addAll(personLeaseMessageService.findTimeStampLongByPersonLease(personLeaseMessage));
            }
        }

        PersonLeaseQueryVo personLeaseQueryVo=new PersonLeaseQueryVo();
        personLeaseQueryVo.setProductId(productId);
        personLeaseQueryVo.setLeaseStates("0,1");
        List<PersonLeaseMessage> personLeaseMessageList=personLeaseMessageService.findPersonLeaseMessage(personLeaseQueryVo);
        List<TimeStampLong> useTimeStampLongList=new ArrayList<TimeStampLong>();
        for (PersonLeaseMessage personLeaseMessage:personLeaseMessageList){
            useTimeStampLongList.addAll(personLeaseMessageService.findTimeStampLongByPersonLease(personLeaseMessage));
        }

        TreeMap<String,List<String>> resultMap=new TreeMap<String,List<String>>();

   /*     Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1,
                               Map.Entry<String, Integer> o2) {
//              System.out.println(o1.getKey()+"   ===  "+o2.getKey());
                return (o1.getKey()).toString().compareTo(o2.getKey().toString());
            }
        });*/

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat1=new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try{
            while (startDate.before(endDate) || startDate.equals(endDate)){
                List<String> list=new ArrayList<String>();
                String dayStart=simpleDateFormat.format(startDate);
                String start=dayStart+" "+startTime;
                String end=dayStart+" "+endTime;
                Date tempStartDate=simpleDateFormat1.parse(start);
                Date endStartDate=simpleDateFormat1.parse(end);
                while (tempStartDate.before(endStartDate)){
                    int startStamp=TimeUtils.toMini(tempStartDate);
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(tempStartDate);
                    cal.add(Calendar.MINUTE, minutes);
                    tempStartDate=cal.getTime();
                    int endStamp=TimeUtils.toMini(tempStartDate);
                 /*1可以使用，0已被购买，2不可使用*/
                    String s="2";
                    for (TimeStampLong checkTimeStampLong:allTimeStampLongList){
                        int checkStart=checkTimeStampLong.getStartTimeStamp();
                        int checkEnd=checkTimeStampLong.getEndTimeStamp();
                        if(startStamp>=checkStart && endStamp<=checkEnd){
                            s="1";
                            break;
                        }
                    }

                    if("1".equals(s)){

                        for (TimeStampLong checkTimeStampLong:canTimeStampLongList){
                            int checkStart=checkTimeStampLong.getStartTimeStamp();
                            int checkEnd=checkTimeStampLong.getEndTimeStamp();
                            if (startStamp>=checkStart && endStamp<=checkEnd){
                                s="1";
                                break;
                            }else{
                                s="2";
                            }
                        }
                        for (TimeStampLong checkTimeStampLong:useTimeStampLongList){
                            int checkStart=checkTimeStampLong.getStartTimeStamp();
                            int checkEnd=checkTimeStampLong.getEndTimeStamp();
                            if(startStamp>=checkEnd || endStamp<=checkStart){
                                continue;
                            }else {
                                s="0";
                                break;
                            }
                        }
                    }

                    list.add(s);

                }
                int weekNum=TimeUtils.getWeekOfDate(startDate);
                String weekName=weekNameArray[weekNum];
                list.add(0,weekName);
                resultMap.put(simpleDateFormat.format(startDate),list);
                Calendar cal = Calendar.getInstance();
                cal.setTime(startDate);
                cal.add(Calendar.DATE,1);
                startDate=cal.getTime();
            }
        }catch (Exception e){
            throw new BusException(e.getMessage());
        }


        return resultMap;
    }

    @Override
    public Boolean checkHaveRoom(SysUser sysUser, Long campusId,Long roomId) {
        DataPermission dataPermission = sysDataPermissionService.findDataPermissionForUser(sysUser.getUserId());
        List<Long> areaTeamIdList=dataPermission.getAreaTeamIds();

        /*检查是否拥有该课室的权限*/
        Boolean noHave=true;
        Campus campus=campusService.findById(campusId);
        if (areaTeamIdList.contains(campus.getAreaTeamId())){
            noHave=false;
        }
        return  noHave;
    }

    @Override
    public Boolean checkHaveAllRoomTime(Long profitMainAccountId, Long campusId) {
        Boolean noHave=true;
        Campus campus=campusService.findById(campusId);
        if (profitMainAccountId.equals(campus.getAreaTeamId())){
            noHave=false;
        }
        return noHave;
    }

    @Override
    public void updateCategoryNames(String oldCategoryName, String newCategoryName, Long categoryId) {
        autoMapper.updateCategoryNames(oldCategoryName,newCategoryName,categoryId);
    }

    @Override
    public void updateCategoryName(String categoryName, Long categoryId) {
        ServiceProduct serviceProduct=new ServiceProduct();
        serviceProduct.setCategoryName(categoryName);
        Example example=ServiceProduct.createExample();
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("categoryId",categoryId);
        this.updateSelectiveByExample(serviceProduct,example);
    }
}